<template>
    <div class="page-container clue-page" ref="pageContainer">
        <div class="table-container">
            <div class="table-header">
                <div class="i-flex i-flex-ai-c">
                    <div class="table-title i-flex-auto">
                        数据线索
                    </div>
                    <div class="i-flex-none" v-if="hasData &&  $hasPermission('all')">
                        <el-button type="primary" @click="handleExportExcel()">
                            导出
                        </el-button>
                    </div>
                </div>
                <div style="margin-top: 15px;">
                    <el-date-picker
                            v-model="date"
                            type="daterange"
                            range-separator="到"
                            start-placeholder="Start date"
                            end-placeholder="End date"
                            format="yyyy-MM-dd"
                            :clearable="false"
                            @change="handleChangeDate">
                    </el-date-picker>
                </div>
            </div>

            <div class="model-box margin not-bottom shadow-box radius" v-if="multipleSelection.length">
                <div class="i-flex i-flex-ai-c ">
                    <div class="i-flex-none">
                        已选{{ multipleSelection.length }}个
                    </div>
                    <div class="i-flex-none " style="margin-left: 10px;">
                        <el-button size="small" type="primary" @click="handleOpenDistribution">
                            分配
                        </el-button>
                    </div>
                </div>
                <el-dialog title="分配线索"
                           :visible.sync="dialogVisible"
                           width="40%">
                    <div style="margin-bottom: 10px;font-size: 12px;">
                        选择员工
                    </div>
                    <el-select v-model="selectValue" :loading="selectLoading" placeholder="选择员工">
                        <el-option
                                v-for="item in selectOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary"
                                   :disabled="!selectValue"
                                   :loading="dialogSubmitLoading"
                                   @click="handleSubmitDistribution">
                            确认
                        </el-button>
                    </div>
                </el-dialog>
            </div>
            <div class="model-box margin shadow-box radius">
                <template v-if="hasData">
                    <div class="table-content" ref="tableContent">
                        <clueTable @selection="handleSelectionChange"
                                   :data="data"
                                   :fields="fields"
                                   :height="tableContentHeight"/>
                    </div>
                    <div class="table-pagination">
                        <el-pagination background
                                       @current-change="handleCurrentChange"
                                       layout="total, sizes, prev, pager, next"
                                       @size-change="handleSizeChange"
                                       :page-sizes="[10, 25, 50, 100]"
                                       :page-size="pageSize"
                                       :total="meta.total || 0">
                        </el-pagination>
                    </div>
                </template>
                <div v-else>
                    么有数据
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import moment                                       from 'moment';
    import { mapState, mapActions }                     from 'vuex'
    import tableContent                                 from '../../mixins/tableContentHeight';
    import clueTable                                    from './clue-table';
    import { fields, clueSource, gender, clueTypeList } from './fields';
    import { apiRequest }                               from "../../assets/fetch";
    import loading                                      from '../../mixins/loading';
    import pagination                                   from '../../mixins/pagination';
    import download                                     from '../../assets/download'


    const oneDay = 3600 * 1000 * 24;

    const today = new Date();
    const week  = new Date();
    const month = new Date();
    week.setTime(week.getTime() - oneDay * 7);
    month.setTime(month.getTime() - oneDay * 30);

    export default {
        mixins    : [ tableContent, loading, pagination ],
        components: {
            clueTable,
        },
        data() {
            const type = this.$route.meta.type;
            return {
                type,
                fields,
                clueTypeList,
                gender,
                clueSource,
                selectLoading      : false,
                selectValue        : '',
                selectOptions      : [],
                date               : [ week, today ],
                count              : null,
                selected           : false,
                dialogSubmitLoading: false,
                multipleSelection  : [],
                cacheId            : '',
                dialogVisible      : false,
            }
        },
        methods   : {
            ...mapActions({
                getData     : 'clue/getDataForType',
                distribution: 'clue/distribution',
                userForType : 'User/userForType',
            }),
            async handleSubmitDistribution() {
                let id = this.multipleSelection.map(item => item.id);

                this.dialogSubmitLoading = true;
                let res                  = await this.distribution({
                    id,
                    userId: this.selectValue,
                });
                this.multipleSelection   = [];
                this.dialogClose();
                if (res.result) {
                    this.$message({
                        message: '分配成功',
                        type   : 'success'
                    });
                    this.handleInit('重载数据..');
                }
                else {
                    this.$message({
                        message: '发送错误',
                        type   : 'error'
                    });
                }
            },
            dialogClose() {
                this.dialogVisible       = false;
                this.dialogSubmitLoading = false;
            },
            handleOpenDistribution() {
                this.handleGetUserList();
                this.dialogVisible = true;
            },
            async handleGetUserList() {
                this.selectLoading = true;
                let res            = await this.userForType(this.type);
                this.selectLoading = false;
                if (res.result) {
                    this.selectOptions = res.data;
                }
                else {

                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            translateDataToTable(data) {
                let fields = this.fields;
                return data.map(e => {
                    let obj = {};
                    for (let key in e) {
                        obj[ fields[ key ] || key ] = e[ key ];
                    }
                    return obj;
                })
            },
            async handleExportExcel() {
                let res = await apiRequest('CLUE_EXCEL', {
                    data: {
                        type: this.type,
                        ...this.dateRange,
                    },
                }, '',true);
                window.location = res;
                // download(res.data , 'Detail_Blast.xlsx');
                console.log('res :', res);
            },
            async handleGetData() {
                return await this.getData({
                    type     : this.type,
                    page_size: this.pageSize,
                    page     : this.currentPage,
                    ...this.dateRange
                });
            },
            async handleInit(text = '数据初始化中...') {
                // this.setLoading(true, text);
                this.showLoading();
                await this.handleGetData();
                this.closeLoading();
                // this.setLoading();
            },
            handleChangeDate() {
                this.handleInit('正在穿梭时间隧道...');
            }
        },
        mounted() {
            this.handleInit();
        },
        computed  : {
            ...mapState({
                data(state) {
                    return state.clue.data || [];
                },
                meta(state) {
                    return state.clue.meta || {};
                }
            }),
            hasData() {
                return !!(this.data && this.data.length);
            },
            dateRange() {
                const date = this.date;
                return {
                    start_time: moment(date[ 0 ]).format('YYYY-MM-DD'),
                    end_time  : moment(date[ 1 ]).format('YYYY-MM-DD'),
                }
            },
        }

    }
</script>

<style lang="less">
    .clue-page {
        .el-tabs__header {
            margin: 0;
        }
        .el-tabs__content {
            display: none;
        }

        .table-pagination {
            padding: 10px 0;
        }

    }
</style>

<style lang="less">
    .el-dialog__header {
        border-bottom: 1px solid #e3e8f0;
    }
</style>
